package com.sansan.ultrasound_handpad.fragment.home;

import android.animation.ValueAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.widget.QMUICollapsingTopBarLayout;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.sansan.ultrasound_handpad.R;
import com.sansan.ultrasound_handpad.adaptor.brvah.PcbTaskPositionRecordAdapter;
import com.sansan.ultrasound_handpad.base.BaseFragment;
import com.sansan.ultrasound_handpad.base.MmkvManager;
import com.sansan.ultrasound_handpad.convertor.JsonConverter;
import com.sansan.ultrasound_handpad.entity.PcbTaskPositionRecord;
import com.sansan.ultrasound_handpad.entity.PcbTaskPositionRecordDetail;
import com.sansan.ultrasound_handpad.entity.StaffEntity;
import com.yanzhenjie.kalle.JsonBody;
import com.yanzhenjie.kalle.Kalle;
import com.yanzhenjie.kalle.simple.SimpleCallback;
import com.yanzhenjie.kalle.simple.SimpleResponse;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 程序扫描页面
 */
public class ProcessFragment extends BaseFragment implements View.OnClickListener {

    private final static String TAG = ProcessFragment.class.getSimpleName();

    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    private MediaPlayer mediaPlayer = new MediaPlayer();

    @BindView(R.id.homefragment_feeding_rButton)
    QMUIRoundButton mFeedingBtn;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.collapsing_topbar_layout)
    QMUICollapsingTopBarLayout mCollapsingTopBarLayout;
    @BindView(R.id.topbar)
    QMUITopBar mTopBar;

    LinearLayoutManager mPagerLayoutManager;
    PcbTaskPositionRecordAdapter mAdapter;

    private StaffEntity staffEntity = null;
    private Context context = null;
    private List<PcbTaskPositionRecordDetail> processList = null;
    private String mProductCode = null;
    private String mPcbTaskCode = null;

    private int flag = 1;

    @Override
    protected View onCreateView() {

        if (getArguments() != null) {
            staffEntity = (StaffEntity)getArguments().getSerializable("UserMsg");
        }

        //startFragment(new ProcessFragment());
//        if (mCollapsingTopBarLayout != null) {
//            //mCollapsingTopBarLayout.setTitle("欢迎:" + (staffEntity == null ? "" : staffEntity.getNickname()));
//            if (staffEntity != null){
//                mCollapsingTopBarLayout.setTitle("欢迎:"+ staffEntity.getNickname());
//            }
//        }



        View rootView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_home, null);
        Button btn = rootView.findViewById(R.id.homefragment_feeding_rButton);
        btn.setOnClickListener(this);
        ButterKnife.bind(this, rootView);



        //初始化标题布局
        if (staffEntity != null){
            mCollapsingTopBarLayout.setTitle("欢迎:"+ staffEntity.getNickname());
        }
        if (mFeedingBtn != null) {
            mFeedingBtn.setVisibility(View.GONE);
        }

        initAdapter();
        mPagerLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(mPagerLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        //设置空白布局
        mAdapter.setEmptyView(getScanCodeView()); //

        mCollapsingTopBarLayout.setScrimUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Log.i(TAG, "scrim: " + animation.getAnimatedValue());
            }
        });

        mCollapsingTopBarLayout.addOnOffsetUpdateListener(new QMUICollapsingTopBarLayout.OnOffsetUpdateListener() {
            @Override
            public void onOffsetChanged(QMUICollapsingTopBarLayout layout, int offset, float expandFraction) {
                Log.i(TAG, "offset = " + offset + "; expandFraction = " + expandFraction);
            }
        });
        return rootView;
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        if (mAdapter == null) {
            mAdapter = new PcbTaskPositionRecordAdapter();
            mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                @Override
                public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                    if (view.getId() == R.id.pcb_taskposition_record_rv_item_cb) {
                        Toast.makeText(getActivity(), "勾选了第" + position + "个", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 扫描获取程序信息界面
     */
    private View getScanCodeView() {

        flag =  1;
        //onCreateView();
//        if (getArguments() != null) {
//            staffEntity = (StaffEntity)getArguments().getSerializable("UserMsg");
//        }
        if (mCollapsingTopBarLayout != null) {
            //mCollapsingTopBarLayout.setTitle("欢迎:" + (staffEntity == null ? "" : staffEntity.getNickname()));
            if (staffEntity != null){
                mCollapsingTopBarLayout.setTitle("欢迎:"+ staffEntity.getNickname());
            } else {
                startFragment(new UserFragment());
                mCollapsingTopBarLayout.setTitle("欢迎:");
            }
        }

        mTopBar.addLeftTextButton("员工退出",R.id.user_exit_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                //builder.setTitle("退出登录");
                builder.setMessage("确定退出当前员工吗?");
                builder.setCancelable(true);
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //Toast.makeText(getActivity(),"点击了确定！",Toast.LENGTH_SHORT).show();
                                startFragment(new UserFragment());
                            }
                        });
                builder.setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //Toast.makeText(getActivity(),"点击了取消！",Toast.LENGTH_SHORT).show();
                            }
                        });

                final AlertDialog dlg = builder.create();
                dlg.show();
                //startFragment(new UserFragment());
            }
        });

        View errorView = getLayoutInflater().inflate(R.layout.scanning_code_obtainrecrd_layout, mRecyclerView, false);
        errorView.findViewById(R.id.scanning_code_obtainrecord_rButton).setOnClickListener(v -> {
            //Toast.makeText(getActivity(), "点击了程序扫码按钮", Toast.LENGTH_SHORT).show();
            //获取程序列表
            obtainPcbTaskPostionRecord(null, null, null);
        });
        return errorView;
    }
//
//    /**
//     * 带输入框的对话框(填写接口调用的ip和端口)
//     */
//    private void showEditTextDialog() {
//        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());
//        builder.setTitle("设置IP地址")
//                .setSkinManager(QMUISkinManager.defaultInstance(getContext()))
//                .setPlaceholder("在此输入您的IP")
//                .setDefaultText(obtainIP())
//                .setInputType(InputType.TYPE_CLASS_TEXT)
//                .addAction("取消", new QMUIDialogAction.ActionListener() {
//                    @Override
//                    public void onClick(QMUIDialog dialog, int index) {
//                        dialog.dismiss();
//                    }
//                })
//                .addAction("确定", new QMUIDialogAction.ActionListener() {
//                    @Override
//                    public void onClick(QMUIDialog dialog, int index) {
//                        if (MmkvManager.getInstance().getMMKV().encode("PAD_IP", builder.getEditText().getText().toString())) {
//                            Toast.makeText(getActivity(), "设置成功", Toast.LENGTH_SHORT).show();
//                            dialog.dismiss();
//                        } else {
//                            Toast.makeText(getActivity(), "设置失败", Toast.LENGTH_SHORT).show();
//                        }
//                    }
//                })
//                .create(mCurrentDialogStyle).show();
//    }


    /**
     * 扫码广播
     */
    /*接收扫码器传回来的扫码数据*/
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            /*扫描数据*/
            byte[] scanData = intent.getByteArrayExtra("barocode");
            /*数据长度*/
            int dataLen = intent.getIntExtra("length", 0);
            /*数据类型*/
            byte dataTyp = intent.getByteExtra("barcodeType", (byte)0);
            /*条码字符串*/
            String barcodeStr = new String(scanData, 0, dataLen);
            Log.d(TAG, "BroadcastReceiver: " + barcodeStr);
            /**
             * 获取程序信息
             */
            if (!TextUtils.isEmpty(barcodeStr)) {
                if (flag == 1) {  //获取程序的3个参数
                    String[] params = barcodeStr.split(";");
                    if (params.length != 3) {
                        ToastUtil.showToast(getActivity(),"扫描获取的参数异常!");
                    } else {
                        /*获取程序信息*/
                        mPcbTaskCode = params[2];
                        obtainPcbTaskPostionRecord(params[0], params[1], params[2]);
                    }
                }

            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();

        if (getActivity() == null) {
            return;
        }
        /*注册扫描器广播*/
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("urovo.rcv.message");
        getActivity().registerReceiver(this.mScanReceiver, intentFilter);
    }

    @Override
    public void onPause() {
        super.onPause();

        if (getActivity() == null) {
            return;
        }
        /*注销扫描器广播*/
        getActivity().unregisterReceiver(this.mScanReceiver);
    }

    /**
     * 获取IP地址和端口
     */
    private String obtainIP() {
        return MmkvManager.getInstance().getMMKV().decodeString("PAD_IP", "http://192.168.0.192:8756/");
    }

    /**
     * 从服务器获取程序信息
     */
    public void obtainPcbTaskPostionRecord(String deviceCode, String pcbId, String pcbTaskCode) {
        JSONObject object = null;
        try {
            object= new JSONObject();
            object.put("deviceCode", deviceCode);
            object.put("pcbId", pcbId);
            object.put("processTaskCode", pcbTaskCode);
        } catch (JSONException e) {
            object = null;
        }

        if (object == null) {
            return;
        }

        Kalle
                .post(obtainIP() + "PcbTaskPositionRecord/buildPositionRecordAndReturn")
                .body(new JsonBody(object.toString()))
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<PcbTaskPositionRecord>() {
                    @Override
                    public void onResponse(SimpleResponse<PcbTaskPositionRecord, String> response) {
                        try {
                            Log.d(TAG, "obtainPcbTaskPostionRecord_onResponse: " + response.succeed());
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                        if (response.isSucceed()) {
                            if (mAdapter != null) {
                                if (mAdapter.hasEmptyView()) {
                                    mAdapter.removeEmptyView();
                                    //mAdapter.setEmptyView(deviceCode,pcbTaskCode);
                                }
                                System.out.println(response.succeed());
                                System.out.println(111);
                                PcbTaskPositionRecord record = response.succeed();
                                if (!(response.succeed() instanceof PcbTaskPositionRecord)) {
                                    Log.d(TAG, "onResponse: 不是PcbTaskPositionRecord类型" + response.succeed());
                                    return;
                                }
                                if (record.getDetailList() != null && record.getDetailList().size() > 0) {
                                    if (processList == null) {
                                        processList = new ArrayList<>(response.succeed().getDetailList());
                                    } else {
                                        processList.clear();
                                        processList.addAll(response.succeed().getDetailList());
                                    }
                                    mAdapter.setNewData(processList);
                                    if (mFeedingBtn != null) {
                                        mFeedingBtn.setVisibility(View.VISIBLE);
                                    }
                                    LoadFragment loadFragment = new LoadFragment();
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("UserMsg", staffEntity);
                                    bundle.putSerializable("processList",(Serializable) processList);
                                    bundle.putSerializable("deviceCode",deviceCode);
                                    bundle.putSerializable("pcbId",pcbId);
                                    bundle.putSerializable("processTaskCode",pcbTaskCode);
                                    //System.out.println(processList.toString());
                                    loadFragment.setArguments(bundle);
                                    startFragment(loadFragment);

                                    //startFragment(new LoadFragment());
                                    //flag = 2; //进入程序列表显示界面
                                    //startPositonRecord(pcbTaskCode,staffEntity.getNickname());
                                }
                            }
                        }
                    }
                });
    }

}
